<template>
	<el-drawer v-model="visible" :before-close="handleBeforeClose" :title="!selectData.id ? '新增散件合包' : '修改散件合包'"
		:close-on-click-modal="true" :size="1400">
		<el-form ref="selectFormRef" :inline="true" :model="selectData" :rules="selectRules">
			<el-row v-if="!selectData.id" class="row-bg" justify="space-between">
				<el-col :span="3">
					<el-select v-model="tableData.businessState" placeholder="业务类型" remote filterable clearable
						@clear="resetSearch">
						<el-option v-for="item in businessList" :key="item.value" :label="item.label"
							:value="item.value" />
					</el-select>
				</el-col>
				<el-col :span="3">
					<el-input v-model="tableData.collectNo" placeholder="收据单号" clearable
						@clear="resetSearch"></el-input>
				</el-col>
				<el-col :span="3">
					<el-input v-model="tableData.collectSmallNo" placeholder="货编号" clearable
						@clear="resetSearch"></el-input>
				</el-col>
				<el-col :span="3">
					<el-input v-model="tableData.expressNo" placeholder="快递编号" clearable
						@clear="resetSearch"></el-input>
				</el-col>
				<el-col :span="3">
					<el-input v-model="tableData.goodsName" placeholder="货名" clearable @clear="resetSearch"></el-input>
				</el-col>
				<el-col :span="3">
					<el-select v-model="tableData.customId" placeholder="客户" remote filterable clearable
						@clear="resetSearch">
						<el-option v-for="item in customerList" :key="item.value" :label="item.label"
							:value="item.value" />
					</el-select>
				</el-col>
			</el-row>
			<div v-if="!selectData.id" style="margin: 10px 0">
				<el-button type="primary" @click="getDataList">查询</el-button>
			</div>

			<el-table v-if="!selectData.id" ref="tableRef" v-loading="dataListLoading" :data="dataList" border
				style="width: 100%" @select-all="handleSelectAll" @select="handleSelect">
				<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
				<el-table-column prop="shoujv_no" label="收据单号" header-align="center" align="center"></el-table-column>
				<el-table-column prop="huobian_no" label="货编号" header-align="center" align="center"></el-table-column>
				<el-table-column prop="origin_country" label="始发地国家" header-align="center" align="center" width="150">
					<template #default="{ row }">
						{{ row.origin_country }}
					</template>
				</el-table-column>
				<el-table-column prop="destination_country" label="目的地国家" header-align="center" align="center"
					width="150">
					<template #default="{ row }">
						{{ row.destination_country }}
					</template>
				</el-table-column>
				<el-table-column prop="business_state" label="业务类型" header-align="center" align="center" width="150">
					<template #default="{ row }">
						<el-tag v-if="row.business_state === '海运'">{{ row.business_state }}</el-tag>
						<el-tag v-else-if="row.business_state === '空运'" type="success">{{ row.business_state }}</el-tag>
						<el-tag v-else type="info">{{ row.business_state }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="collect_name" label="货名" header-align="center" align="center"
					width="150"></el-table-column>
				<el-table-column label="货物类型" header-align="center" align="center" width="150">
					<template #default="{ row }">
						<el-tag v-if="row.collect_type === 0">普货</el-tag>
						<el-tag v-else-if="row.collect_type === 1" type="success">敏感货</el-tag>
						<el-tag v-else-if="row.collect_type === 2" type="info">单证普货</el-tag>
						<el-tag v-else type="warning">单证敏感货</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="customer_name" label="客户" header-align="center" align="center"
					width="150"></el-table-column>
			</el-table>
			<el-pagination v-if="!selectData.id" :current-page="tableData.currentPage" :page-sizes="pageSizes"
				:page-size="tableData.pageSize" :total="tableData.total"
				layout="total, sizes, prev, pager, next, jumper" @size-change="sizeChangeHandle"
				@current-change="currentChangeHandle">
			</el-pagination>
			<div v-if="!selectData.id" class="line" />

			<el-row class="form-row" :gutter="20">
				<el-col :span="5">
					<el-form-item label-width="50px" label="箱号" prop="boxNo">
						<el-input v-model="selectData.boxNo" readonly> </el-input>
					</el-form-item>
					<el-form-item label-width="50px" label="箱数" prop="boxNum">
						<el-input v-model="selectData.boxNum" readonly> </el-input>
					</el-form-item>
					<el-form-item label-width="50px" label="箱重" prop="boxWeight">
						<el-input v-model="selectData.boxWeight"> </el-input>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="箱长(cm)" prop="boxLength">
						<el-input v-model="selectData.boxLength"></el-input>
					</el-form-item>
					<el-form-item label-width="50px" label="箱宽" prop="boxWidth">
						<el-input v-model="selectData.boxWidth"> </el-input>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label-width="50px" label="箱高" prop="boxHeight">
						<el-input v-model="selectData.boxHeight"> </el-input>
					</el-form-item>
					<el-form-item label="体积(m³)">
						<el-input v-model="TiJi" readonly> </el-input>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label-width="50px" label="货重">
						<el-input v-model="formatNumberWithCommas" type="text" readonly> </el-input>
					</el-form-item>
					<el-form-item label="体积重(kg)">
						<el-input v-model="TijiWeight" type="text" readonly> </el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>

		<template #footer>
			<el-button @click="closeDrawer()">取消</el-button>
			<el-button type="primary" @click="submitHandle(selectFormRef)">确定</el-button>
		</template>
	</el-drawer>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus/es'
import { getExpressRelatedDataApi } from '@/api/hourse'
import type { FormInstance, FormRules } from 'element-plus'
import { collectExpressSmallApi, selectPackList, getExpressRelatedData } from '@/api/freight'
import { fetchWarning, myError } from '@/store/modules/common'
import { reactive, ref, watch, computed, onMounted, nextTick, defineExpose } from 'vue'
import { getBoxNO, add, getSelectPrint, getSelectOrder, packCollectUpdateApi } from '@/api/pack'

const visible = ref(false)
const dataListLoading = ref(false)
const dataList = ref([])
const selectedGoods = ref(<any>[]);

const emit = defineEmits(['refreshDataList'])

const tableData = reactive({
	collectNo: '',
	customId: '',
	salesman: '',
	customer: '',
	businessState: '',
	goodsName: '',
	expressNo: '',
	collectSmallNo: '',
	currentPage: 1,
	pageSize: 10,
	total: 0
})

const selectData = reactive({
	id: '',
	boxNo: '',
	boxNum: 0,
	expressWeight: '',
	boxWeight: '',
	boxLength: '',
	boxWidth: '',
	boxHeight: '',
	tiji: '',
	tijiWeight: '',
	collectExpressIdlist: [] as Array<string | number>,
	destinationCountry: '', //目的地国家
	originCountry: '', //始发地国家
	businessState: '' //业务类型
})
const selectRules: FormRules = reactive({
	boxLength: [{ required: true, message: '请输入长', trigger: 'blur' }],
	boxWidth: [{ required: true, message: '请输入宽', trigger: 'blur' }],
	boxHeight: [{ required: true, message: '请输入高', trigger: 'blur' }],
	boxWeight: [{ required: true, message: '请输入箱重', trigger: 'blur' }]
})

//箱号
const getboxNum = async () => {
	try {
		const res = await getBoxNO() // 获取返回的数据
		// 直接检查返回的数据的 `code`
		if (res.code === 0) {
			selectData.boxNo = res.data
		} else {
			// 如果不需要提示错误，可以直接返回
			return
		}
	} catch (error) {
		// 处理请求错误（例如网络问题）
		console.error('获取箱号时出错:', error)
		// 如果需要处理错误的逻辑，可以放在这里
	}
}
getboxNum()

//分页
const pageSizes = [1, 2, 5, 10, 20, 100]
const isPagination = ref(true)
const sizeChangeHandle = (val: number) => {
	tableData.pageSize = val
	console.log('sizeChangeHandle', val)
	getDataList()
}
const currentChangeHandle = (val: number) => {
	tableData.currentPage = val
	console.log('currentChangeHandle', val)

	getDataList()
}
const tableRef = ref(null)
const getDataList = async () => {
	const obj = {
		page: tableData.currentPage,
		pageSize: tableData.pageSize
	}

	dataListLoading.value = true
	const params = { ...obj, ...tableData }
	try {
		const res = await collectExpressSmallApi(params)
		console.log('返回数据', res)

		dataListLoading.value = false
		if (fetchWarning(res)) {
			return
		}
		if (res.data === '') {
			isPagination.value = false
		}
		if (res.data.length === 1 && dataList.value.length > 0) {
			console.log('自动勾选:', res.data[0])
		}

		// 更新数据列表
		const beforeSelect = selectData.collectExpressIdlist

		dataList.value = res.data.records
		tableData.currentPage = res.data.current
		tableData.total = res.data.total
		tableData.pageSize = res.data.size
	} catch (e) {
		dataListLoading.value = false
		myError(e)
	}
}

getDataList()
const resetSearch = () => {
	tableData.collectNo = ''
	tableData.collectSmallNo = ''
	tableData.expressNo = ''
	tableData.goodsName = ''
	tableData.customId = ''
	tableData.businessState = ''
	getDataList()
}
const init = (data = {}) => {
	console.log('data', data)
	dataListLoading.value = true
	if (data) {
		Object.assign(selectData, data)
	} else {
		resetFormData()
	}
	visible.value = true
	dataListLoading.value = false
}
const selectFormRef = ref<FormInstance | null>(null)
const resetFormData = () => {
	for (const key in selectData) {
		if (Array.isArray(selectData[key])) {
			selectData[key] = []
		} else {
			selectData[key] = ''
		}
	}
}
const closeDrawer = () => {
	visible.value = false
	resetFormData()
}
const handleBeforeClose = (done: () => void) => {
	resetFormData()
	done()
}


const submitHandle = (formEl: any) => {
	if (!formEl) {
		return false
	}

	formEl.validate( (valid: boolean) => {
		if (!valid) {
			ElMessage.error('请完整填写表单')
			return false
		}

		if (selectData.collectExpressIdlist.length > 1) {
			// 当勾选多个时，校验 destinationCountry 和 businessState 是否一致
			let destinationCountry = selectedGoods.value[0].destination_country;
			let businessState = selectedGoods.value[0].business_state;

			const isValid = selectedGoods.value.every(
				item => item.destination_country === destinationCountry && item.business_state === businessState
			)
			if (!isValid) {
				ElMessage.error('目的地国家或业务类型不一致，请选择相同的国家和业务类型')
				return false
			}
		}
		
		// 如果验证通过，开始提交数据
		if(selectData.id){
			packCollectUpdateApi(selectData).then(() => {
				ElMessage.success({
					message: '操作成功',
					duration: 500,
					onClose: () => {
						visible.value = false
						emit('refreshDataList')
					}
				})
			})
		}else{
			add(selectData).then(() => {
				ElMessage.success({
					message: '操作成功',
					duration: 500,
					onClose: () => {
						visible.value = false
						emit('refreshDataList')
					}
				})
			})
		}
		
	})
}


const formatNumberWithCommas = computed(() => {
	return selectData.expressWeight.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
})

// 表格行选择事件处理
const handleSelect = (
	selection: any[],
	row: { id: string | number; origin_country: string; destination_country: string; business_state: string }
) => {
	console.log(row.destination_country)

	const isSelect = selection.find((item: { id: any }) => item.id === row.id)
	if (!isSelect) {
		selectData.collectExpressIdlist = selectData.collectExpressIdlist.filter(item => item !== row.id)
	} else {
		selectData.collectExpressIdlist.push(row.id)
	}
	selectData.boxNum = selectData.collectExpressIdlist.length

	if (selection.length > 1) {
		selectData.originCountry = selection[0].origin_country
		selectData.destinationCountry = selection[0].destination_country
		selectData.businessState = selection[0].business_state
	} else if (selection.length === 1) {
		selectData.originCountry = row.origin_country
		selectData.destinationCountry = row.destination_country
		selectData.businessState = row.business_state
	}

	const totalWeight = selection.reduce((total: any, item: { collect_weight: any }) => total + item.collect_weight, 0)
	selectData.expressWeight = totalWeight.toFixed(2)

	selectedGoods.value = selection;
}

// 表格全选事件处理
const handleSelectAll = (selection: any[]) => {
	const isSelectAll = selection.length > 0
	if (isSelectAll) {
		selection.forEach(item => {
			if (!selectData.collectExpressIdlist.includes(item.id)) {
				selectData.collectExpressIdlist.push(item.id)
			}
		})
	} else {
		selectData.collectExpressIdlist = []
	}
	selectData.boxNum = selectData.collectExpressIdlist.length

	if (selection.length > 0) {
		selectData.originCountry = selection[0].origin_country
		selectData.destinationCountry = selection[0].destination_country
		selectData.businessState = selection[0].business_state
	}

	const totalWeight = selection.reduce((total, item) => total + item.collect_weight, 0)
	selectData.expressWeight = totalWeight.toFixed(2)

	selectedGoods.value = selection;
}
//体积重
const TijiWeight = computed(() => {
	return (selectData.tijiWeight = ((selectData.boxLength * selectData.boxWidth * selectData.boxHeight) / 6000).toFixed(3))
})
//体积
const TiJi = computed(() => {
	return (selectData.tiji = ((selectData.boxLength * selectData.boxWidth * selectData.boxHeight) / 1000000).toFixed(3))
})

//常用业务类型
const businessList = ref([])
const customerList = ref([])

const getExpressRelatedData = async () => {
	try {
		const res = await getExpressRelatedData()
		console.log('getExpressRelatedData', res.data)
		// businessList.value = [{ label: '全部业务类型', value: 'All' }, ...res.data.businessTypeList.slice(1, 3)]
		customerList.value = res.data.customerList.map((item: { name: any; id: any }) => ({
			label: item.name,
			value: item.id
		}))
		businessList.value = res.data.businessTypeList
	} catch (e) {
		console.log(e)
	}
}
getExpressRelatedData()

defineExpose({
	init
})
</script>
<style scoped>
.line {
	float: right;
	width: 100%;
	height: 1px;
	margin-top: 50px;
	background: #d4c4c4;
	position: relative;
	text-align: center;
}

.form-row {
	margin-top: 70px;
	margin-bottom: 20px;
	/* Adjust the margin as needed */
}

.col-style {
	margin-left: 10px;
}
</style>
(: { name: any; id: any }): { origin_country: string; destination_country: string; business_state: string; id: string |
number }(: { id: any }): any:
{ collect_weight: any }(: { name: any; id: any })
